<?php
// +----------------------------------------------------------------------
// | 小说系统 [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------

use think\Db;

function int_to_string(&$data, $map = array('status' => array(1 => '正常', -1 => '删除', 0 => '禁用', 2 => '未审核', 3 => '草稿'))) {
	if ($data === false || $data === null) {
		return $data;
	}
	$data = (array) $data;
	foreach ($data as $key => $row) {
		foreach ($map as $col => $pair) {
			if (isset($row[$col]) && isset($pair[$row[$col]])) {
				$data[$key][$col . '_text'] = $pair[$row[$col]];
			}
		}
	}
	return $data;
}

/**
 * 获取对应状态的文字信息
 * @param int $status
 * @return string 状态文字 ，false 未获取到
 * @author huajie <banhuajie@163.com>
 */
function get_status_title($status = null) {
	if (!isset($status)) {
		return false;
	}
	switch ($status) {
	case -1:return '已删除';
		break;
	case 0:return '禁用';
		break;
	case 1:return '正常';
		break;
	case 2:return '待审核';
		break;
	default:return false;
		break;
	}
}

// 获取数据的状态操作
function show_status_op($status) {
	switch ($status) {
	case 0:return '启用';
		break;
	case 1:return '禁用';
		break;
	case 2:return '审核';
		break;
	default:return false;
		break;
	}
}

/**
 * 获取行为类型
 * @param intger $type 类型
 * @param bool $all 是否返回全部类型
 * @author huajie <banhuajie@163.com>
 */
function get_action_type($type, $all = false) {
	$list = array(
		1 => '系统',
		2 => '用户',
	);
	if ($all) {
		return $list;
	}
	return $list[$type];
}

	/**
	 * 获取行为数据
	 * @param string $id 行为id
	 * @param string $field 需要获取的字段
	 */
	function get_action($id = null, $field = null) {
		if (empty($id) && !is_numeric($id)) {
			return false;
		}
		$list = cache('action_list');
		if (empty($list[$id])) {
			$map       = array('status' => array('gt', -1), 'id' => $id);
			$list[$id] = db('Action')->where($map)->field(true)->find();
		}
		return empty($field) ? $list[$id] : $list[$id][$field];
	}

	function my_scandir($dir)
		{  
		 $files=array();  
		 if(is_dir($dir)){  
			if($handle=opendir($dir)){
				while(($file=readdir($handle))!==false){  
					if($file!='.' && $file!=".."){  
						$path = $dir."/".$file; // 设置目录，用于含有子目录的情况 
						if(is_dir($path)){  
							$files[$file]=my_scandir($path);  
						}else{
							$filename[] = $path;//获取文件名称
							$files[]=$dir."/".$file;
						} 
					}
				}  
			}  
		 }  
		 closedir($handle);
		 //array_multisort($filetime,SORT_DESC,SORT_STRING,$files);//按时间排序
		 //array_multisort($filename,SORT_ASC,SORT_STRING, $files);//按名字排序
		 return $files;  
	}

	/****复制文件*****/
	function copyfile($from_file, $to_file, $mode = 511, $move = false)
	{
		$from_file = trim($from_file);

		if (!is_file($from_file)) {
			return false;
		}

		$to_file = trim($to_file);
		$matches = array();
		
		checkdir(dirname($to_file), true);

		if (is_file($to_file)) {
			@unlink($to_file);
		}

		if ($move) {
			$ret = rename($from_file, $to_file);
		}
		else {
			$ret = copy($from_file, $to_file);
		}

		if ($ret && $mode) {
			@chmod($to_file, $mode);
		}

		return $ret;	
	}
	
    /**
      * zipfolder [解压文件]
      *
      * @param type $target_dir  [当前解压目录]
      * @param type $upfilePath  [上传ZIP的目录]
      * @param type $newfilePath [解压以后移动的目录]
      * @param type $file_dir    [网站根目录]
      * @param type $ebook       [文件路径]
      *
      * @return array
    **/
	function zipfolder($target_dir,$upfilePath,$newfilePath,$file_dir,$ebook){
		$zip = zip_open($file_dir.$ebook);
		if ($zip)
		{
		   while ($zip_entry = zip_read($zip))
		   {
			if (zip_entry_open($zip, $zip_entry, "r"))
			{
			 $buf = zip_entry_read($zip_entry,zip_entry_filesize($zip_entry));// 读取zip文件, 并制定读取的长度
			 $fname = $target_dir.'/'.zip_entry_name($zip_entry);
			 if(is_dir($fname))                    // 如果是目录则创建目录(目录是未创建的)
			 {
				 checkdir($fname, 1 );
			 }else{
				 checkdir(dirname($fname), 1 );
				if(strpos($fname,'.jpg') !==false || strpos($fname,'.png') !==false || strpos($fname,'.gif') !==false){
					file_put_contents($fname,$buf); 
				}
			 }
			 zip_entry_close($zip_entry);
			}
		   }
		   zip_close($zip);
		}			
		$files = my_scandir($target_dir);
		asort($files);//降序
		//对文件进行排序
		$array_imgs = array();
		if($files){
			foreach($files  as $key=>$val){
				$new_array= array();
				$sort_array = array();
				foreach($val as $v){
					$sort_array[$v] = $v;
				}			
				asort($sort_array);//降序
				
				foreach($sort_array as $k=>$v){
					$filename =$newfilePath.date('Ymd')."/".getRandomName($v);
					copyfile($v,dirname(APP_PATH).$filename, 511, true);
					$new_array[] = $filename;
				}					
				$array_imgs[$key] = $new_array;
			}
		}
		//删除解压目录
		delfolder($target_dir);
		delfolder($upfilePath);
		return $array_imgs;
	}
	
    /**
      * get_agent [desc]
      *
      * @param type $id  [获取推广的URL]
      * @param type $uid [desc]
      * @param type $short_url[强制关闭短连接]
      * @return type
    **/
	function get_agent($id,$uid,$wxmpid=0,$short_url=true){
		$result = db('member')->find($uid);
		$wxmpid=$wxmpid?$wxmpid:session('wxmpid');
		$agent_tuiguangurl = config('agent_tuiguangurl');
		$site_url = config('web_site_url');
		$url = '';
		$wxmp = array();
		
		//渠道用户
		if($result['is_top']==1  || in_array($result['group'],[4,8,9,10])){
			//渠道服务号是否存在
			$wxmp = db('wxmp')->where(['id'=>$wxmpid,'status'=>1])->field('id,open_appid')->find();
			if($wxmp){
				$url = get_agent_domain($uid,$wxmp['open_appid'],$wxmp['id'])."/referrals/index/".$id;
			}else{
				$url = $site_url."/referrals/index/".$id;
			}
		}else{
			//代理商对应的渠道用户服务号是否存在
			$wxmp = db('wxmp')->where(['id'=>$wxmpid,'status'=>1])->field('id,open_appid')->find();
			if($wxmp&&$result['s_uid']!=1&&$result['s_uid']){
				$url = get_agent_domain($result['s_uid'],$wxmp['open_appid'],$wxmp['id'])."/referrals/index/".$id;
			}else{
				$url = $site_url."/referrals/index/".$id;
			}
		}

		if(config('sina_short_url')&&$short_url){
			return getSinaShortUrl($url);
		}else{
			return $url;
		}
		
	}
	
    
	
    /**
      * get_appid [获取APPID]
      *
      * @param type $uid [用户ID]
      *
      * @return type
    **/
	function get_appid($uid,$wxmpid=0){
		$result = db('member')->find($uid);
		
		$appid = config('wx_apiid');
		
		//渠道用户
		if($result['is_top']==1){
			//渠道服务号是否存在
			$wxmp = db('wxmp')->where(['id'=>$wxmpid,'status'=>1])->find();
			if($wxmp){
				$appid = $wxmp['appid'];
			}
		}elseif($result['s_uid']>0){
			//代理商对应的渠道用户服务号是否存在
			$wxmp = db('wxmp')->where(['id'=>$wxmpid,'status'=>1])->find();
			if($wxmp){
				$appid = $wxmp['appid'];
			}
		}
		return $appid;
	}
	
	
    /**
      * get_payinfo [获取用户支付信息]
      *
      * @param type $uid [desc]
      *
      * @return type
    **/
	function get_payinfo($uid){
		$payinfo = db('MemberExtend')->where('uid',$uid)->find();
		$info = '';
		switch($payinfo['payment_type']){
			case 'bank':
				$info .="<p>收款方式：银行卡</p>";
				break;
			case 'alipay':
				$info .="<p>收款方式：支付宝</p>";
				break;
			case 'weixin':
				$info .="<p>收款方式：微信</p>";
				break;
			default:
				$info .="<p>收款方式：未配置</p>";
		}
		if($payinfo['payment_type'] =='bank'){
			$info .="<p>持卡人姓名：".$payinfo['card_holder_name']."</p>";
			$info .="<p>卡号：".$payinfo['card_number']."</p>";
			$info .="<p>开户行：".$payinfo['card_bank_name'].$payinfo['card_bank_province'].$payinfo['card_bank_city'].$payinfo['card_bank_branch']."</p>";
		}elseif($payinfo['payment_type'] =='alipay'){
			$info .="<p>帐号：".$payinfo['alipay_account_number']."</p>";
			$info .="<p>姓名：".$payinfo['alipay_account_name']."</p>";
		}elseif($payinfo['payment_type'] =='weixin'){
			$info .="<p>微信号：".$payinfo['weixin_account']."</p>";
			$info .="<p>昵称：".$payinfo['weixin_nickname']."</p>";
		}
		return $info;
	}

		/**
	 * 调用新浪接口将长链接转为短链接
	 * @param  string        $source    申请应用的AppKey
	 * @param  array|string  $url_long  长链接，支持多个转换（需要先执行urlencode)
	 * @return array
	 */
	function getSinaShortUrl($url_long){
		$wechat = load_wechat(1,'Extends');
		$url_long = $wechat->getShortUrl($url_long);
		return $url_long;
	}

	function get_spread($bookid,$urltype){
		$num = Db::connect("database.db_config_two")->name('tuiguang')->where(['modelid'=>1,'articleid'=>$bookid,'urltype'=>$urltype])->count();
		return $num?$num:0;
	}
	function get_category_list($bookid){
		$num = Db::connect("database.db_config_two")->name('third_category')->where(['id'=>$bookid])->find();
		return $num['title']?$num['title']:$bookid;
	}
	/**
     * 一维数据数组生成数据树
     * @param array $list 数据列表
     * @param string $id 父ID Key
     * @param string $pid ID Key
     * @param string $son 定义子数据Key
     * @return array
     */
    function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'sub')
    {
        list($tree, $map) = [[], []];
        foreach ($list as $item) {
            $map[$item[$id]] = $item;
        }
        foreach ($list as $item) {
            if (isset($item[$pid]) && isset($map[$item[$pid]])) {
                $map[$item[$pid]][$son][] = &$map[$item[$id]];
            } else {
                $tree[] = &$map[$item[$id]];
            }
        }
        unset($map);
        return $tree;
    }

	/**
      * paySum [活动充值金额]
	  
      * @return type
    **/
	function get_activity_amount($activityid,$type='',$daytime='') {
		
		$wxmpid = session('wxmpid');
		$map['status'] = 1;
		$map['is_kouliang'] = 0;

		if($activityid){
			$map['activityid'] = $activityid;
		}

		if($type=="today"){
			$starttime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$endtime = mktime(23,59,59,date('m'),date('d'),date('Y'));
			$map['update_time'] = array(array('>=',$starttime),array('<=',$endtime));
		}elseif($type=="history"){
			$starttime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$map['update_time'] = array('<',$starttime);
		}

		if($daytime){
			$starttime = mktime(0,0,0,date('m',$daytime),date('d',$daytime),date('Y',$daytime));
			$endtime = mktime(23,59,59,date('m',$daytime),date('d',$daytime),date('Y',$daytime));
			$map['update_time'] = array(array('>=',$starttime),array('<=',$endtime));
		}

		if(session('user_auth.group')!=999){
			$map['agentid'] = array('in',get_agent_user(session('user_auth.uid')));
			$map['wxmpid'] = $wxmpid;
		}

		$sum = db('order')->where($map)->cache(true,600)->sum('money');

		return $sum?$sum:0;
	}
	//自定义活动充值
	function get_diyactivity_amount($activityid,$type='',$field='payegold') {
		
		$wxmpid = session('wxmpid');
		
		if($activityid){
			$map['activityid'] = $activityid;
		}

		if($type=="today"){
			$starttime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$endtime = mktime(23,59,59,date('m'),date('d'),date('Y'));
			$map['update_time'] = array(array('>=',$starttime),array('<=',$endtime));
		}elseif($type=="history"){
			$starttime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$map['update_time'] = array('<',$starttime);
		}

		if($daytime){
			$starttime = mktime(0,0,0,date('m',$daytime),date('d',$daytime),date('Y',$daytime));
			$endtime = mktime(23,59,59,date('m',$daytime),date('d',$daytime),date('Y',$daytime));
			$map['update_time'] = array(array('>=',$starttime),array('<=',$endtime));
		}

		if(session('user_auth.group')!=999){
			$map['uid'] = array('in',get_agent_user(session('user_auth.uid')));
			$map['wxmpid'] = $wxmpid;
		}

		$sum = db('promotionStatistics')->where($map)->cache(true,600)->sum('money');

		return $sum?$sum:0;
	}

	/**
      * statistics [活动充值笔数]
      *
	  
      * @return type
    **/
	function get_activity_paynum($activityid,$type='') {
		
		$wxmpid = session('wxmpid');
		$map['status'] = 1;
		$map['is_kouliang'] = 0;
		
		if($activityid){
			$map['activityid'] = $activityid;
		}

		if($type=="today"){
			$starttime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$endtime = mktime(23,59,59,date('m'),date('d'),date('Y'));
			$map['update_time'] = array(array('>=',$starttime),array('<=',$endtime));
		}elseif($type=="history"){
			$starttime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$map['update_time'] = array('<',$starttime);
		}

		if(session('user_auth.group')!=999){
			$map['agentid'] = array('in',get_agent_user(session('user_auth.uid')));
			$map['wxmpid'] = $wxmpid;
		}

		$total = db('order')->where($map)->count();
		
		return $total;
	}
	/**
      * get_activity [自定义活动统计]
      *
      * @param type $activityid [自定义活动ID]
      * @param type $field      [输出的字段]
      * @param type $type       [时间类别 today：今天 history：历史（不含当日）]
      *
      * @return type
    **/
	function get_activity($activityid,$field="view",$type="") {

		$wxmpid = session('wxmpid');

		if($activityid){
			$map['activityid'] = $activityid;
		}

		if($type=="today"){
			$starttime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$endtime = mktime(23,59,59,date('m'),date('d'),date('Y'));
			$map['date'] = array(array('>=',$starttime),array('<=',$endtime));
		}elseif($type=="history"){
			$starttime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$map['date'] = array('<',$starttime);
		}


		if(session('user_auth.group')!=999){
			$map['uid'] = array('in',get_agent_user(session('user_auth.uid')));
			$map['wxmpid'] = $wxmpid;
		}

		$sum = db('promotionStatistics')->where($map)->cache(true,600)->sum($field);

		return $sum?$sum:0;	
	}

	

	function get_agent_user($uid) {
		$member = db('member')->where('uid='.$uid)->find();
		
		if($member['is_top']==1){
			$map['s_uid'] = $uid;
		}/***elseif($member['is_top']==0 && empty($member['t_uid'])){
			$map['t_uid'] = $uid;
		}***/else{
			return $uid;
		}
		$map['status'] =1;
		$map['group'] =array('IN','3,4');
		
		$daili = db('member')->where($map)->cache(true,600)->column('uid');
		$daili[]=$uid;
		$agentid = implode(",",$daili);
		return $agentid;
	}
	
	//获取用户充值数据
	function get_userpay($uid,$type="total"){
		
		if($type=="total"){
			$res = db('order')->where("uid=$uid and status=1")->cache(true,600)->count();
		}else{
			$res = db('order')->where("uid=$uid and status=1")->cache(true,600)->sum('money');
		}

		return  $res;
	}

	function get_diyprice($articleid,$field=''){
		$wxmpid = session('wxmpid');
		$uid = session('user_auth.uid');
		$diyprice = db('diyprice')->where("uid",$uid)->where("wxmpid",$wxmpid)->where("articleid",$articleid)->find();
		if($diyprice){
			if($field){
				return $diyprice[$field];
			}else{
				return true;
			}
		}else{
			return false;
		}
	}

	/**
      * get_tracktx [腾讯回传数据汇总]
      *
      * @param type $type [1:回传金额 2：回传订单数]
      *
      * @return type
    **/
	function get_tracktx($type,$trackid){
		$startdata = mktime(0,0,0,date('m'),date('d'),date('Y'));
		$enddata = mktime(23,59,59,date('m'),date('d'),date('Y'));
		$map['create_time'] = array(array('gt',$startdata),array('lt',$enddata));
		
		$map['tid'] =$trackid;
		if($type==1){
			$result = db('track_tengxun_log')->where($map)->cache(true,600)->sum('money');
		}else{
			$result = db('track_tengxun_log')->where($map)->count();
		}
		return $result?$result:0;
	}


	/**
	 * 查小说来源
	 */
	function getCpsCpMember($id = 0)
	{
		$res = Db::connect("database.db_config_two")->name('cp_member')->select();
		if($id>-1){
			foreach ($res as $k => $v) {
				if($v['uid'] == $id){
					return $v['nickname'];
				}
			}
			return $id ==0 ? '本站': '未知';
		}
		return $res;
		# code...
	}
	

	/**
	 * 检查标识权限, 例如
	 * 是否有编辑权限 checkAuthRule('edit');
	 * 规则需要配置  admin/material/index_1_1_edit
	 * 				控制器名称/方法名称_edit
	 * $tag  标识 
	 * $auto 默认true 自动补全控制器与方法， 如需自己写则 checkAuthRule(admin/material/index_1_1_edit', false)
	 * @Author 小邓
	 * @DateTime 2022-11-12
	 * @return void
	 */
	function checkAuthRule($tag, $auto=true, $uid=null){
		$tag    = strtolower( $auto ? MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME.'_'.$tag : $tag );
		// echo $tag;exit;
        $group  = session('user_auth.group');
        $uid    = $uid?:session('user_auth.uid');
        if($group == 999){
            return true;
        }
        $user_rules      = db("member")->where("uid", $uid)->cache(true, 10)->value('rules');
        $group_rules     = db("auth_group")->where("id", $group)->cache(true, 10)->value('rules');
        $user_rules_arr  = explode(',',$user_rules);  // 用户单独权限
        $group_rules_arr = explode(',',$group_rules); // 用户组权限
        $rules = array_merge($user_rules_arr, $group_rules_arr);
        $group = db("auth_rule")->where("id","in", $rules)->cache(true, 10)->column('name', 'id');
        foreach ($group as $k => $v) {
            $group[$k] = strtolower($v);
        }
		// dump($group);exit;
        return in_array($tag, $group) ? true : false;
	}

	/**
	 * 时间显示
	 *
	 * @Author 小邓
	 * @DateTime 2022-11-17
	 * @param [type] $time
	 * @return void
	 */
	function mdate($time = NULL) {
		if(stristr($time, "-")){
			$time = strtotime($time);
		}
		$int = time() - $time;
		$str = '';
		if ($int <= 30){
			$str = sprintf('刚刚', $int);
		}elseif ($int < 60){
			$str = sprintf('%d秒前', $int);
		}elseif ($int < 3600){
			$str = sprintf('%d分钟前', floor($int / 60));
		}elseif ($int < 86400){
			$str = sprintf('%d小时前', floor($int / 3600));
		}elseif ($int < 2592000){
			$str = sprintf('%d天前', floor($int / 86400));
		}else{
			$str = date('Y-m-d H:i:s', $time);
		}
		return $str;
	}

	function toUtf8($str) {
		$encode = mb_detect_encoding($str, array('CP936', "ASCII","GB2312","GBK",'UTF-16', 'UCS-2', 'UTF-8','BIG5'));
		if ($encode == 'UTF-8') {
			return $str;
		} elseif ($encode == 'CP936') {
			return iconv('utf-8', 'latin1//IGNORE', $str);
		} else {
			return mb_convert_encoding($str, 'UTF-8', $encode);
		}
	}

	/**
	 * 格式化字符
	 *
	 * @Author 小邓
	 * @DateTime 2022-11-18
	 * @param [type] $content
	 * @return void
	 */
	function douyin_str_format( $content ) {
		 $content = $test =  str_replace([PHP_EOL],"####",htmlspecialchars_decode( $content, ENT_QUOTES ));
		 $content  =  str_replace('########', "####",  $content);
		 $content  =  str_replace(["\r\n", "\r", "\n", PHP_EOL],"",   $content);
		 $content  =  str_replace(['################', "########"], "####",  $content);
		return $content;
	}

	/**
	 * 日志记录
	 *
	 * @Author 小邓
	 * @DateTime 2022-11-19
	 * @param [type] $id
	 * @param [type] $platform_id
	 * @return void
	 */
	function action_log2($id, $platform_id,$act = 'edit'){
		try {
			if(is_array($id)) {
				$id = implode("," , $id);
			}
			
			if(stristr($id, ",")){
				$ids = explode(",", $id);
				$id = $ids[0]??0;
			}else{
				$ids = [$id];
			}
			$ids = array_splice($ids, 0, 100);
			$ids = implode("," , $ids);
			$arr = [
				['id' => 1, 'name' => "百度"],
				['id' => 2, 'name' => "知乎"],
				['id' => 3, 'name' => "抖音"],
				['id' => 4, 'name' => "微博"],
				['id' => 5, 'name' => "腾讯"],

				['id' => 'baidu_text', 'name' => "百度文案"],
				['id' => 'douyin_text', 'name' => "抖音文案"],
				['id' => 'weibo_text', 'name' => "微博文案"],
				['id' => 'img', 'name' => "图片"],
				['id' => 'video', 'name' => "视频"],
				['id' => 'bgm', 'name' => "音频"],
				
			];
			
			$arr = array_column($arr, "name", "id");
			if(stristr($platform_id, ",")){
				$platform_ids = explode(",", $platform_id);
				$platform = "";
				foreach ($platform_ids as $id) {
					$platform .= $arr[$id] ?? "其它";
				}
			}else{
				$platform = $arr[$platform_id] ?? "其它";
			}
			
			$action = ACTION_NAME;
			$ref = isset($_SERVER ["HTTP_REFERER"]) ? trim(str_replace(".html", "",parse_url($_SERVER ["HTTP_REFERER"])['path']).'_'.$action, "/"): '';
			
			$ref = str_replace("down_txt", "down", $ref);
			$ref = str_replace("down_douyin_txt", "down", $ref);
			$ref = str_replace("change_status", "status", $ref);
			$ref = str_replace("uploadmaterial", "upload", $ref);
			
			$ref = preg_replace('/_my\$/','',$ref);;
			if($act == 'edit'){
				$ref = str_replace("add", "edit", $ref);
			}
			$table = CONTROLLER_NAME;
			$uid     = session('user_auth.uid');
			action_log($ref, $table, $id, $uid, ['platform'=> $platform, "ids" => $ids]);
		} catch (\Throwable $th) {
			// throw $th;
		}

	}